package cn.tedu.order.service;

import cn.tedu.order.entity.AccountMessage;
import cn.tedu.order.entity.Order;
import cn.tedu.order.entity.TxInfo;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.mapper.TxMapper;
import cn.tedu.order.util.JsonUtil;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
@RocketMQTransactionListener //监听器  RocketMQLocalTransactionListener接口
public class OrderServiceImpl implements OrderService, RocketMQLocalTransactionListener{
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private RocketMQTemplate t;
    @Autowired
    private TxMapper txMapper;

    @Override
    public void create(Order order){
        String xid = UUID.randomUUID().toString().replace("-", "");
        AccountMessage am = new AccountMessage(order.getUserId(), order.getMoney(), xid);
        //am --> Json
        String json = JsonUtil.to(am);
        //spring封装的通用message对象
        //payLoad会自动被转换成一个byte[]
        Message<String> message = MessageBuilder.withPayload(json).build();

        //发送事务消息
        //如果添加Tag,格式:  orderTopic:TagA
//        t.sendMessageInTransaction("orderTopic",message,业务数据参数 )
        t.sendMessageInTransaction("orderTopic",message,order );
    }

    @Transactional
    public void doCreate(Order order) {
        // TODO: 从全局唯一id发号器获得id
        String s = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(s);
        order.setId(orderId);
        orderMapper.create(order);
    }
    @Transactional
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        RocketMQLocalTransactionState state;//用来返回
        int status;//用来存储到数据库

        try{
            Order order=(Order)o;
            doCreate(order);//业务
            state=RocketMQLocalTransactionState.COMMIT;
            status=0;
        }catch (Exception e){
            e.printStackTrace();
            state=RocketMQLocalTransactionState.ROLLBACK;
            status=1;
        }
        //TxInfo 封装事务状态
        String json = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(json, "xid");//从Json中直接取出想要的数据
        TxInfo txInfo = new TxInfo(xid, status, System.currentTimeMillis());
        txMapper.insert(txInfo);
        return state;
    }
    @Transactional
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String json = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(json, "xid");//从Json中直接取出想要的数据
        TxInfo txInfo = txMapper.selectById(xid);
        if (txInfo==null){
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        switch (txInfo.getStatus()){
            case 0: return RocketMQLocalTransactionState.COMMIT;
            case 1: return RocketMQLocalTransactionState.ROLLBACK;
            default: return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
